import React from 'react'
import { message } from 'antd'
import { awaitWrap, strToNum } from '@js/tool'
import { computeFee } from '@js/fee'
import { getClaimItemConfigRequest } from '../ajax/claim'

export const ClaimContext = React.createContext({
  claimItemConfig: [], // 请求类型可选项
  claimItemFeeConfig: [], // 请求项费用配置
  setClaimItemFeeConfig: () => {},
  changeClaimItemFeeConfig: () => {},
  removeClaimItemFeeConfing: () => {}, // 删除某个仲裁请求配置项
  computeClaimFee: () => {} // 计算费用
})

// 设置请求项费用配置
export function changeClaimItemFeeConfig (formRef, name, beforeHandle = () => {}, callback = () => {}, claimItemFeeConfig, index = -1, rules = []) {
  beforeHandle(claimItemFeeConfig)
  if (index === -1 || !formRef.current) {
    return false
  }
  const c = formRef.current
  const d = c.getFieldsValue()
  const item = {
    ...d[name].items[index],
    dispute_amount: 0,
    fee_acceptance: 0,
    fee_processing: 0
  }
  rules.forEach(r => {
    item[r.key] = r.default_value ? Number(r.default_value) : 0
  })
  d[name].items[index] = item
  c.setFieldsValue(d)
  callback()
}

// 删除某个仲裁请求配置项
export function removeClaimItemFeeConfing (index, claimItemFeeConfig, callback) {
  const list = [...claimItemFeeConfig]
  list.splice(index, 1)
  callback(list)
}

// 获取仲裁请求项配置
async function getClaimItemConfig () {
  const [e, d] = await awaitWrap(getClaimItemConfigRequest())
  if (e) {
    return message.warning(e.message)
  }
  return d
}

// 初始化数据
export function initData (callback = () => {}) {
  const hide = message.loading('加载中', 120)
  Promise.all([getClaimItemConfig.call(this)])
    .then(([claimItemConfig]) => {
      hide()
      const d = { claimItemConfig }
      callback(d)
    })
    .catch(e => {
      hide()
    })
}

// 展开子节点，生成一个扁平数组
function flatChildren (list) {
  let result = []
  list.forEach(li => {
    result.push(li)
    if (li.children && li.children.length) {
      result = [...result, ...flatChildren(li.children)]
    }
  })
  return result
}

// 格式化仲裁请求和仲裁请求布局
export function formatClaim (claimItemConfig, claim, originClaim, formRef, name, changeClaimItemFeeConfig) {
  const flatClaimItemConfig = flatChildren(claimItemConfig)
  const titles = flatClaimItemConfig.map(li => li.title)
  const claimItemFeeConfig = []
  if (claim.items.length === 0) {
    claim.items = [{ type: '标的收费', dispute_amount: 0 }]
  }
  claim.items = claim.items.map(li => {
    const index = titles.indexOf(li.type)
    if (index === -1) {
      li.type = []
      claimItemFeeConfig.push([])
    } else {
      const config = flatClaimItemConfig[index]
      li.type = [...config.titles]
      claimItemFeeConfig.push(config.json_rule)
    }
    return {
      desc: li.desc,
      type: li.type,
      dispute_amount: li.dispute_amount,
      fee: li.fee,
      fee_acceptance: li.fee_acceptance,
      fee_processing: li.fee_processing
    }
  })
  changeClaimItemFeeConfig(claimItemFeeConfig)
  const res = { items: claim.items }
  if (originClaim && originClaim.fee_type) {
    res.fee_type = originClaim.fee_type
  }
  formRef.current.setFieldsValue({ [name]: res })
  if (originClaim) {
    computeClaimFee(formRef, name, originClaim)
  }
}

// 计算费用
export function computeClaimFee (formRef, name, originClaim) {
  const c = formRef.current
  const claim = c.getFieldsValue([name])[name]
  if (!claim) {
    return undefined
  }
  let disputeAmount = 0
  let acceptanceFee = 0
  let processingFee = 0
  claim.items.forEach(li => {
    if (!li) {
      return false
    }
    if (li.dispute_amount) {
      disputeAmount += strToNum(li.dispute_amount)
    }
    if (li.fee_acceptance) {
      acceptanceFee += strToNum(li.fee_acceptance)
    }
    if (li.fee_processing) {
      processingFee += strToNum(li.fee_processing)
    }
  })
  claim.dispute_amount = Number(disputeAmount.toFixed(2))
  const result = computeFee(disputeAmount, strToNum(claim.fee_type))
  if (disputeAmount === 0) {
    if (acceptanceFee > result.fee_acceptance) {
      result.fee_acceptance = acceptanceFee
    }
  } else {
    result.fee_acceptance += acceptanceFee
  }
  result.fee_processing += processingFee
  result.fee = result.fee_acceptance + result.fee_processing
  result.fee_acceptance = Number(result.fee_acceptance.toFixed(2))
  result.fee_processing = Number(result.fee_processing.toFixed(2))
  result.fee = Number(result.fee.toFixed(2))
  if (originClaim) {
    result.fee_acceptance_amend = result.fee_acceptance - originClaim.fee_acceptance
    result.fee_processing_amend = result.fee_processing - originClaim.fee_processing
    result.fee_amend = result.fee_acceptance_amend + result.fee_processing_amend
    result.item_count_amend = claim.items.length - originClaim.items.length
    result.dispute_amount_amend = disputeAmount - originClaim.dispute_amount
    result.fee_acceptance_amend = Number(result.fee_acceptance_amend.toFixed(2))
    result.fee_processing_amend = Number(result.fee_processing_amend.toFixed(2))
    result.fee_amend = Number(result.fee_amend.toFixed(2))
    result.dispute_amount_amend = Number(result.dispute_amount_amend.toFixed(2))
  }
  c.setFieldsValue({
    [name]: {
      ...claim,
      ...result,
      log: undefined
    }
  })
}

// 自定义费用并备注原因
export function computeFeeWithLog (d, name, formRef, originClaim, callback) {
  const c = formRef.current
  let claim = c.getFieldsValue([name])[name]
  if (originClaim) {
    d.fee_acceptance_amend = d.fee_acceptance - originClaim.fee_acceptance
    d.fee_processing_amend = d.fee_processing - originClaim.fee_processing
    d.fee_amend = strToNum(d.fee_acceptance_amend) + strToNum(d.fee_processing_amend)
  }
  claim = {
    ...claim,
    ...d
  }
  c.setFieldsValue({ [name]: claim })
  callback()
}

// 计算项数变化
export function computeItemCount (formRef, name, originClaim) {
  const c = formRef.current
  const claim = c.getFieldsValue([name])[name]
  if (originClaim) {
    claim.item_count_amend = claim.items.length - originClaim.items.length
  }
  c.setFieldsValue({
    [name]: {
      ...claim
    }
  })
}
